package com.example.simplejson4android;

import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import com.example.simplejson4android.clazz.VideoQueryInfo;
import com.google.gson.Gson;
import com.simple.json.Sjson;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// runWithGson(1000);
		// runWithSjson(1000);
		runWithSjson(1);
	}

	private void runWithSjson(final int times) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					InputStream jsonIs = getAssets().open("json.txt");
					final String jsonStr = inputStream2String(jsonIs);
					long sTime = 0;
					for (int i = 0; i < times; i++) {
						long startTimeS = System.currentTimeMillis();
						VideoQueryInfo infoS = Sjson.jsonToObject(jsonStr,
								VideoQueryInfo.class);
						long endTimeS = System.currentTimeMillis();
						long costTimeS = endTimeS - startTimeS;
						sTime += costTimeS;
						infoS = null;
					}
					Log.d("json", "Sjson " + times + "次， 总共耗时： " + sTime
							+ ", 平均每次耗时:" + (sTime / times));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	private void runWithGson(final int times) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					InputStream jsonIs = getAssets().open("json.txt");
					final String jsonStr = inputStream2String(jsonIs);

					Gson gson = new Gson();
					long gTime = 0;
					for (int i = 0; i < times; i++) {
						long startTimeG = System.currentTimeMillis();
						VideoQueryInfo infoG = gson.fromJson(jsonStr,
								VideoQueryInfo.class);
						long endTimeG = System.currentTimeMillis();
						long costTimeG = endTimeG - startTimeG;
						gTime += costTimeG;
						infoG = null;
					}
					Log.d("json", "Gson " + times + "次， 总共耗时： " + gTime
							+ ", 平均每次耗时:" + (gTime / times));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	public String inputStream2String(InputStream in) throws IOException {
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}

}
